package cn.mju.tankfighterbackend.config.websocket

import org.apache.catalina.security.SecurityUtil
import org.slf4j.LoggerFactory
import org.springframework.http.server.ServerHttpRequest
import org.springframework.http.server.ServerHttpResponse
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.security.web.context.support.SecurityWebApplicationContextUtils
import org.springframework.stereotype.Component
import org.springframework.web.socket.WebSocketHandler
import org.springframework.web.socket.server.HandshakeInterceptor
import java.lang.Exception

/**
 * 在连接升级的时候注入userId信息给websocket服务使用
 */
@Component
class HandShakeInterceptor: HandshakeInterceptor {
    val logger = LoggerFactory.getLogger(this.javaClass)
    override fun beforeHandshake(
        request: ServerHttpRequest,
        response: ServerHttpResponse,
        wsHandler: WebSocketHandler,
        attributes: MutableMap<String, Any>
    ): Boolean {
        request.principal?.let {
            attributes["userName"] = it.name
            return true
        }
        logger.warn("未检测到userName")

        return false
    }

    override fun afterHandshake(
        request: ServerHttpRequest,
        response: ServerHttpResponse,
        wsHandler: WebSocketHandler,
        exception: Exception?
    ) {

    }

}
